// 创建性能监控插件
import { onMounted, onUnmounted } from 'vue'

const VuePerformancePlugin = {
  install(app, options = {}) {
    const defaultOptions = {
      log: true,
      trackComponents: false,
      sampleRate: 0.1,
      endpoint: null,
      longTaskThreshold: 200
    }
    
    const config = { ...defaultOptions, ...options }
    const performanceData = {
      components: {},
      metrics: {},
      longTasks: []
    }

    // 1. 初始化性能观察器
    const initPerformanceObserver = () => {
      if (!window.PerformanceObserver) return
      
      // 长任务监控
      const longTaskObserver = new PerformanceObserver((list) => {
        list.getEntries().forEach(entry => {
          if (entry.duration > config.longTaskThreshold) {
            performanceData.longTasks.push(entry)
            logPerformance('longtask', entry)
          }
        })
      })
      longTaskObserver.observe({ type: 'long-task', buffered: true })

      // 核心Web指标监控
      const coreWebObserver = new PerformanceObserver((list) => {
        list.getEntries().forEach(entry => {
          performanceData.metrics[entry.entryType] = entry
          logPerformance(entry.entryType, entry)
        })
      })
      coreWebObserver.observe({
        type: ['largest-contentful-paint', 'first-input-delay', 'layout-shift'],
        buffered: true
      })
    }

    // 2. 性能数据记录
    const logPerformance = (type, data) => {
      if (config.log) {
        console.log(`[Performance ${type}]`, data)
      }
      
      if (config.endpoint && Math.random() <= config.sampleRate) {
        sendToServer(type, data)
      }
    }

    // 3. 数据上报
    const sendToServer = (type, data) => {
      const body = JSON.stringify({
        type,
        data,
        timestamp: Date.now(),
        url: window.location.href,
        userAgent: navigator.userAgent
      })
      
      if (navigator.sendBeacon) {
        navigator.sendBeacon(config.endpoint, body)
      } else {
        fetch(config.endpoint, {
          method: 'POST',
          body,
          keepalive: true
        })
      }
    }

    // 4. 组件级监控
    if (config.trackComponents) {
      app.mixin({
        mounted() {
          if (this.$options.performanceMark) {
            const mark = `${this.$options.performanceMark}-${this._uid}`
            performance.mark(`${mark}-start`)
            
            onMounted(() => {
              performance.mark(`${mark}-end`)
              performance.measure(
                mark,
                `${mark}-start`,
                `${mark}-end`
              )
              
              const measure = performance.getEntriesByName(mark)[0]
              const componentName = this.$options.name || 'Anonymous'
              
              performanceData.components[componentName] = 
                performanceData.components[componentName] || []
              performanceData.components[componentName].push(measure.duration)
              
              logPerformance('component', {
                name: componentName,
                duration: measure.duration
              })
            })
          }
        }
      })
    }

    // 5. 路由监控
    if (app.config.globalProperties.$router) {
      app.config.globalProperties.$router.beforeEach((to) => {
        performance.mark(`route-${to.name}-start`)
      })
      
      app.config.globalProperties.$router.afterEach((to) => {
        performance.mark(`route-${to.name}-end`)
        performance.measure(
          `route-${to.name}`,
          `route-${to.name}-start`,
          `route-${to.name}-end`
        )
        
        const measure = performance.getEntriesByName(`route-${to.name}`).pop()
        logPerformance('navigation', {
          route: to.name,
          duration: measure.duration
        })
      })
    }

    // 初始化
    initPerformanceObserver()
    
    // 挂载到app实例
    app.config.globalProperties.$performance = {
      data: performanceData,
      track: logPerformance
    }
  }
}

export default VuePerformancePlugin